<template>
  <div class="merchants-container">
    <div class="header">
      <div class="left-section">
        <h2 class="page-title">商户管理</h2>
        <!-- 状态筛选按钮组 -->
        <div class="filter-tabs">
          <div 
            v-for="tab in statusTabs" 
            :key="tab.value"
            :class="['filter-tab', statusFilter === tab.value ? 'active' : '']"
            @click="handleStatusFilterChange(tab.value)"
          >
            {{ tab.label }}
          </div>
        </div>
      </div>
      <div class="actions">
        <div class="search-box">
          <el-input
            :prefix-icon="Search"
            v-model="searchQuery"
            placeholder="搜索商户名称"
            clearable
          />
        </div>
        <el-button type="danger" class="search-btn" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
      </div>
    </div>

    <el-table 
      :data="filteredMerchantList" 
      border 
      stripe 
      style="width: 100%" 
      v-loading="loading"
    >
      <el-table-column prop="merchantId" label="商户ID" align="center">
        <template #header>
          <div class="header-text">
            商户ID
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="商户名称" align="center" />
      <el-table-column prop="registrationDate" label="注册日期" align="center">
        <template #header>
          <div class="header-text">
            注册日期
          </div>
        </template>
        <template #default="scope">
          {{ formatDate(scope.row.registrationDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="productCount" label="商品数量" align="center">
        <template #header>
          <div class="header-text">
            商品数量
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="salesAmount" label="销售额" align="center">
        <template #header>
          <div class="header-text">
            销售额
          </div>
        </template>
        <template #default="scope">
          ¥{{ scope.row.salesAmount ? scope.row.salesAmount.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center" width="120">
        <template #header>
          <div class="filter-header">
            状态
            <el-icon><Filter /></el-icon>
          </div>
        </template>
        <template #default="scope">
          <span
            :class="[
              'status-tag',
              scope.row.status === '正常' ? 'status-normal' : 
              scope.row.status === '待审核' ? 'status-pending' : 
              'status-frozen'
            ]"
          >
            {{ getStatusText(scope.row.status) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <el-button 
            v-if="scope.row.status === '正常'"
            type="danger"
            plain
            size="small" 
            class="action-btn freeze-btn"
            @click="handleFreeze(scope.row)"
          >
            <el-icon><RemoveFilled /></el-icon>
            冻结
          </el-button>
          
          <el-button 
            v-if="scope.row.status === '待审核'"
            type="success"
            plain
            size="small" 
            class="action-btn approve-btn"
            @click="handleApprove(scope.row)"
          >
            <el-icon><Check /></el-icon>
            审核
          </el-button>
          
          <el-button 
            v-if="scope.row.status === '已冻结'"
            type="primary"
            plain
            size="small" 
            class="action-btn unfreeze-btn"
            @click="handleUnfreeze(scope.row)"
          >
            <el-icon><Check /></el-icon>
            解冻
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handlePageChange"
        background
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Filter, 
  RemoveFilled, 
  Check
} from '@element-plus/icons-vue'
import { getAllMerchants, freezeMerchant, unfreezeMerchant, approveMerchant } from '../../api/auth'


// 搜索查询
const searchQuery = ref<string>('')

// 状态筛选
const statusFilter = ref<string>('全部')

// 加载状态
const loading = ref<boolean>(false)

// 状态标签配置
const statusTabs = [
  { label: '全部', value: '全部' },
  { label: '运营中', value: '正常' },
  { label: '已冻结', value: '已冻结' },
  { label: '待审核', value: '待审核' }
]

// 分页相关
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const total = ref<number>(0)

// 商户数据
const merchantList = ref<Merchant[]>([])

// 商户类型定义
interface Merchant {
  _id: string;
  email: string;
  username: string;
  merchantId?: string;
  status: string;
  productCount?: number;
  salesAmount?: number;
  registrationDate?: Date;
}

// 添加商品类型定义
interface Product {
  _id: string;
  name: string;
  price: number;
  image?: string;
  sales: number;
}

// 格式化日期
const formatDate = (dateString: string | Date | undefined): string => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN').replace(/\//g, '-')
}

// 获取状态文字
const getStatusText = (status: string): string => {
  return status || '未知'
}

// 定义API参数接口
interface MerchantParams {
  page: number;
  limit: number;
  status?: string;
  search?: string;
}

// 获取商户列表
const fetchMerchants = async (): Promise<void> => {
  loading.value = true
  try {
    // 构建查询参数
    const params: MerchantParams = {
      page: currentPage.value,
      limit: pageSize.value,
      status: statusFilter.value !== '全部' ? statusFilter.value : undefined,
      search: searchQuery.value || undefined
    }
    
    const response = await getAllMerchants(params)
    
    if (response.data && response.data.code === 200) {
      merchantList.value = response.data.data.map((merchant: Merchant) => ({
        ...merchant,
        salesAmount: merchant.salesAmount || 0,
        productCount: merchant.productCount || 0
      }))
      
      // 更新分页信息
      if (response.data.pagination) {
        total.value = response.data.pagination.total
      } else {
        total.value = merchantList.value.length
      }
    } else {
      ElMessage.error('获取商户列表失败')
    }
  } catch (error) {
    console.error('获取商户列表出错:', error)
    ElMessage.error('获取商户列表出错')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取商户列表
onMounted(() => {
  fetchMerchants()
})

// 处理分页变化
const handlePageChange = (page: number): void => {
  currentPage.value = page
  fetchMerchants()
}

// 处理搜索
const handleSearch = (): void => {
  currentPage.value = 1
  fetchMerchants()
}

// 处理冻结
const handleFreeze = (row: Merchant): void => {
  ElMessageBox.confirm(
    `确定要冻结商户"${row.username}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true
      const response = await freezeMerchant(row._id)
      
      if (response.data && response.data.code === 200) {
        ElMessage.success(`商户${row.username}已冻结`)
        // 更新本地数据
        const index = merchantList.value.findIndex(item => item._id === row._id)
        if (index !== -1) {
          merchantList.value[index].status = '已冻结'
        }
      } else {
        ElMessage.error(response.data?.message || '操作失败')
      }
    } catch (error) {
      console.error('冻结商户失败:', error)
      ElMessage.error('冻结商户失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 处理解冻
const handleUnfreeze = (row: Merchant): void => {
  ElMessageBox.confirm(
    `确定要解冻商户"${row.username}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(async () => {
    try {
      loading.value = true
      const response = await unfreezeMerchant(row._id)
      
      if (response.data && response.data.code === 200) {
        ElMessage.success(`商户${row.username}已解冻`)
        // 更新本地数据
        const index = merchantList.value.findIndex(item => item._id === row._id)
        if (index !== -1) {
          merchantList.value[index].status = '正常'
        }
      } else {
        ElMessage.error(response.data?.message || '操作失败')
      }
    } catch (error) {
      console.error('解冻商户失败:', error)
      ElMessage.error('解冻商户失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 处理审核
const handleApprove = (row: Merchant): void => {
  ElMessageBox.confirm(
    `确定要审核通过商户"${row.username}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(async () => {
    try {
      loading.value = true
      const response = await approveMerchant(row._id)
      
      if (response.data && response.data.code === 200) {
        ElMessage.success(`商户${row.username}已审核通过`)
        // 更新本地数据
        const index = merchantList.value.findIndex(item => item._id === row._id)
        if (index !== -1) {
          merchantList.value[index].status = '正常'
        }
      } else {
        ElMessage.error(response.data?.message || '操作失败')
      }
    } catch (error) {
      console.error('审核商户失败:', error)
      ElMessage.error('审核商户失败')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}


// 由于使用后端分页，直接使用merchantList
const filteredMerchantList = computed<Merchant[]>(() => merchantList.value)

// 处理状态筛选变化
const handleStatusFilterChange = (value: string): void => {
  statusFilter.value = value
  currentPage.value = 1
  fetchMerchants()
}
</script>

<style scoped>
.merchants-container {
  padding: 20px;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 0;
  white-space: nowrap;
}

.merchant-summary {
  display: flex;
  gap: 20px;
}

.summary-item {
  font-size: 14px;
  color: #606266;
}

.summary-value {
  font-weight: bold;
  color: #e6333e;
}

.actions {
  display: flex;
  gap: 15px;
  align-items: center;
}

.search-box {
  width: 300px;
}

.search-btn {
  background-color: #e6333e;
  border-color: #e6333e;
  color: white;
  display: flex;
  align-items: center;
  gap: 5px;
}

.filter-tabs {
  display: flex;
  gap: 10px;
}

.filter-tab {
  padding: 6px 15px;
  border-radius: 16px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  background-color: #f0f0f0;
  transition: 全部 0.3s;
}

.filter-tab.active {
  color: #fff;
  background-color: #e6333e;
}

.filter-header, .header-text {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-normal {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #c2e7b0;
}

.status-pending {
  background-color: #fdf6ec;
  color: #e6a23c;
  border: 1px solid #f5dab1;
}

.status-frozen {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}

.action-btn {
  margin: 0 5px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  border-radius: 4px;
}

.edit-btn {
  color: #fff;
  border-color: #f56c6c;
  background-color: #f56c6c;
}

.freeze-btn {
  color: #fff;
  border-color: #f56c6c;
  background-color: #f56c6c;
}

.approve-btn {
  color: #fff;
  border-color: #67c23a;
  background-color: #67c23a;
}

.unfreeze-btn {
  color: #fff;
  border-color: #409EFF;
  background-color: #409EFF;
}

/* 详情按钮已移除 */

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 分页组件颜色自定义 */
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #e6333e;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #e6333e;
}

:deep(.el-pagination .btn-prev:hover, .el-pagination .btn-next:hover) {
  color: #e6333e;
}

/* 商户详情样式已移除 */ 
</style>